package com.dstz.sys.aop;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.dstz.base.api.response.IResult;

@Aspect
@Component
public class LogAspect {
	private static Logger logController = LoggerFactory.getLogger(LogAspect.class.getName()+".logController");
	private static Logger logManager = LoggerFactory.getLogger(LogAspect.class.getName()+".logManager");
	
    @Pointcut("within(com.dstz.base.manager.Manager+)")
    public void logManager(){}
    
    @Around("logManager()")
    public Object logManager(ProceedingJoinPoint point) throws Throwable {
    	logManager.info("call {}.{}{}", point.getTarget().getClass().getSimpleName(), point.getSignature().getName(), Arrays.toString(point.getArgs()));
    	
    	long beginTime = System.currentTimeMillis();
    	Object result = point.proceed();
    	long time = System.currentTimeMillis() - beginTime;
    	
    	logManager.info("ret({}) {}", time, result);
    	return result;
    }
    
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void logController(){}
    
    @Around("logController()")
    public Object logController(ProceedingJoinPoint point) throws Throwable {
    	HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    	logController.info("{} {}", httpServletRequest.getMethod(), httpServletRequest.getRequestURI());
    	logController.info("{}.{}{}", point.getTarget().getClass().getSimpleName(), point.getSignature().getName(), Arrays.toString(point.getArgs()));
    	
    	long beginTime = System.currentTimeMillis();
    	Object result = point.proceed();
    	long time = System.currentTimeMillis() - beginTime;
    	
    	if(result!=null && result instanceof IResult) {
    		logController.info("END({}) {}", time, JSON.toJSONString(result));
    	}else {
    		logController.info("END({}) {}", time, result);
    	}
    	return result;
    }
}
